package com.yangsir.mysite.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yangsir.mysite.common.R;
import com.yangsir.mysite.pojo.Article;
import com.yangsir.mysite.pojo.Category;
import com.yangsir.mysite.service.ArticleService;
import com.yangsir.mysite.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * java 8
 */
@CrossOrigin
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleService articleService;

    /**
     * 获取所有类别
     * @return
     */
    @GetMapping("/getAllCategory")
    public R<List<Category>> getAllCategory() {
        return R.success(categoryService.list(), "类别获取成功");
    }

    /**
     * 根据id获取类别
     * @param id
     * @return
     */
    @GetMapping("/getCategorysById")
    public R<List<Category>> getCategoryByStr(Long id) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getId, id);
        List<Category> list = categoryService.list(queryWrapper);
        return list == null ? R.success(list, "暂无类别") : R.success(list, "类别获取成功");
    }

    /**
     * 保存类别
     * @param category
     * @return
     */
    @PostMapping("/saveCategorys")
    public R<String> saveCategory(@RequestBody Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getCategoryName, category.getCategoryName());
        if (categoryService.getOne(queryWrapper) != null) {
            return R.error("类别已存在");
        }
        if (!categoryService.save(category)) {
            return R.error("类别保存失败");
        }
        return R.success("类别保存成功");
    }

    /**
     * 删除类别
     * @param id
     * @return
     */
    @DeleteMapping("/deleteCategory")
    public R<String> deleteCategory(Long id) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getCategoryId, id);
        List<Article> list = articleService.list(queryWrapper);
        if (list.isEmpty()) {
            return categoryService.removeById(id) ? R.success("类别删除成功") : R.error("类别删除失败");
        }
        return R.error("请先移除该类别下的文章！");
    }
}
